package org.mtmi.ui.controls.edits;

import org.eclipse.swt.graphics.Rectangle;
import org.mtmi.ui.IAdaptable;
import org.mtmi.ui.IMG;
import org.mtmi.ui.controls.AbstractRangeValueControl;
import org.mtmi.ui.controls.AbstractValueControlledControl;
import org.mtmi.ui.controls.IValueGenerator;
import org.mtmi.ui.controls.listeners.ControlBoundsEvent;
import org.mtmi.ui.controls.listeners.ControlBoundsListener;
import org.mtmi.ui.edit.AbstractSourceControlConnector;
import org.mtmi.ui.layouts.LayoutData;
import org.mtmi.ui.links.CID;
import org.mtmi.ui.links.IConnectable;

/**
 * The idea is to connect an {@link AbstractRangeValueControl} to a IValueGenerator. 
 * 
 */
public class ValueConnector extends AbstractSourceControlConnector
  implements ControlBoundsListener
{
	
	private AbstractValueControlledControl consumer;
	
	public ValueConnector( AbstractValueControlledControl k, int _flags) {
//TODO: image ...		
		super( k.getScene(), IMG.GetD( IMG.I_MIDI_VALUE ), CID.VALUE_CONSUMER, _flags );
		consumer = k;
		
		IValueGenerator vg = consumer.getValueController();
		IConnectable cp = null;
		if( vg instanceof IConnectable ) {
			cp = (IConnectable)vg;
		} 
		else if( vg instanceof IAdaptable ) {
			cp = (IConnectable)((IAdaptable)vg).getAdapter( IConnectable.class, null );
			if( cp==null ) {
				throw new Error("cannot get IConnectionProvider from object: "+vg);
			}
		}
		setConnectedControl( cp, consumer.getValueControllerConnectionId() );
		
		setSize( computeSize( new LayoutData(scene) ) );
		updateLocation();
		
		consumer.addControlBoundsListener( this );
	}
	
	@Override
	public void dispose() {
		consumer.removeControlBoundsListener( this );
		super.dispose();
	}

	@Override
	protected void newConnection( IConnectable c, String cid, int x, int y, String source_cid ) {
		IValueGenerator vg = null;
//TODO: a revoir ....		
		if( c instanceof IValueGenerator ) {
			vg = (IValueGenerator)c;
		} else if( c!=null ) {
			vg = (IValueGenerator)c.getAdapter( IValueGenerator.class, cid );
			if( vg == null ) {
				throw new Error("Cannot make connection: source is incompatible to IValueGenerator");
			}
		}
		consumer.setValueController( vg, cid );
	}

	@Override
	public void controlBoundsChanged(ControlBoundsEvent event) {
		redraw(); //mark old bounds to be redrawn
		updateLocation();
		redraw(); //redraw new bounds
	}
	
	private void updateLocation() {
		Rectangle r = consumer.getBounds(null);
		setLocation( r.x+10, r.y+r.height-size.y/2 );
	}
	
}
